package cl.metlife.contentviewer.servlets;

import cl.metlife.contentstore.ContentRetriever;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cl.metlife.contentstore.RepositoryException;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;

import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;

@WebServlet(urlPatterns = "/cv")
public class ContentViewerServlet extends HttpServlet {

    private Logger logger = Logger.getLogger(ContentViewerServlet.class);

    @EJB
    private ContentRetriever contentRetriever;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {

        /* Recovering the content Key from the request as a parameter */
        String key = "";

        key = request.getParameter("key");
        logger.debug("Key was found on the request");

        /* Retrieving content from the Data Source */
        try {
        String content = contentRetriever.getContent(key);

        /* Generating the content for the user */
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(content);

        } catch(RepositoryException e) {
            logger.error("It was impossible to retrieve the content");
            response.sendError(SC_NOT_FOUND);
        }

    }

}
